package com.jinlejia.feedback.common.databinding;

import android.app.Activity;
import android.content.Context;
import android.view.View;

/**
 * 共同事件
 */

public final class CommonEvent {
    private CommonEvent(){

    }
    private static CommonEvent event;

    public static CommonEvent obtain(){
        if (event==null){
            event = new CommonEvent();
        }
        return event;
    }

    public void back(View view){
        Activity activity = getActivity(view);
        if (activity!=null){
            if (activity instanceof BackFilter){
                boolean canBack = ((BackFilter) activity).onBack();
                if (!canBack && !activity.isFinishing()){
                    activity.finish();
                }
            }else {
                activity.finish();
            }
        }
    }

    private Activity getActivity(View view){
        if (view==null)return null;
        Context context = view.getContext();
        if (context instanceof Activity){
            return (Activity) context;
        }else {
            return getActivity(view.getRootView());
        }
    }

    public interface BackFilter{
        /**
         * 在关闭Activity之前，允许Activity做自己特殊的业务
         * @return true：消化掉Back事件 false:继续关闭Activity
         */
        boolean onBack();
    }
}
